import uuid
from datetime import datetime
from typing import Any
from fastapi import Request
from fastapi import APIRouter, HTTPException
from sqlalchemy.orm import selectinload
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models.community_models import CommunityPostsPublic, CommunityPost, CommunityPostPublic, CommentPublic, \
    Comment, CommunityPostCreate, CommunityPostUpdate, CommentCreate
from pydantic import BaseModel, Field
from uuid import UUID
from datetime import datetime
from datetime import datetime
from typing import Any
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models.community_models import (
    CommunityPostsPublic,
    CommunityPost,
    CommunityPostPublic,
    CommentPublic,
    Comment,
    CommunityPostCreate,
    CommunityPostUpdate,
    CommentCreate,
    PostLike,            # 新增
    CommentLike,         # 新增
    LikeResponse         # 新增
)
from uuid import UUID


router = APIRouter(prefix="/community", tags=["community"])


# -----------------------------------
# 帖子 CommunityPost 接口
# -----------------------------------

# 创建帖子
@router.post("/createPost", response_model=CommunityPostPublic)
def create_post(session: SessionDep, current_user: CurrentUser, post_in: CommunityPostCreate) -> Any:
    post = CommunityPost.model_validate(post_in, update={"user_id": current_user.id})
    session.add(post)
    session.commit()
    session.refresh(post)
    return post

# 获取帖子
@router.get("/posts", response_model=CommunityPostsPublic)
def read_posts(session: SessionDep, skip: int = 0, limit: int = 20) -> Any:
    # 获取总数
    count = session.exec(select(func.count()).select_from(CommunityPost)).one()

    # 修改查询以包含用户信息
    query = (
        select(CommunityPost)
        .options(selectinload(CommunityPost.user))  # 使用 selectinload 加载关联的用户数据
        .order_by(CommunityPost.created_at.desc())
        .offset(skip)
        .limit(limit)
    )
    posts = session.exec(query).all()

    return CommunityPostsPublic(data=posts, count=count)

# 获取单个帖子
@router.get("/posts/{id}", response_model=CommunityPostPublic)
def read_post(session: SessionDep, id: uuid.UUID) -> Any:
    post = session.get(CommunityPost, id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    return post

# 更新帖子
@router.put("/posts/{id}", response_model=CommunityPostPublic)
def update_post(session: SessionDep, current_user: CurrentUser, id: uuid.UUID, post_in: CommunityPostUpdate) -> Any:
    post = session.get(CommunityPost, id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    if post.user_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    update_dict = post_in.model_dump(exclude_unset=True)
    post.sqlmodel_update(update_dict)
    session.add(post)
    session.commit()
    session.refresh(post)
    return post

# 删除帖子
@router.delete("/posts/{id}")
def delete_post(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> dict:
    post = session.get(CommunityPost, id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    if post.user_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    session.delete(post)
    session.commit()
    return {"message": "Post deleted successfully"}

# 获取帖子点赞状态
@router.get("/posts/{post_id}/like-status", response_model=LikeResponse)
def get_post_like_status(
        session: SessionDep,
        current_user: CurrentUser,
        post_id: UUID
) -> Any:
    # 检查帖子是否存在
    post = session.get(CommunityPost, post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")

    # 检查用户是否已点赞
    liked = session.exec(
        select(PostLike)
        .where(PostLike.post_id == post_id)
        .where(PostLike.user_id == current_user.id)
    ).first() is not None

    # 获取点赞总数
    likes_count = session.exec(
        select(func.count()).select_from(PostLike).where(PostLike.post_id == post_id)
    ).one()

    return LikeResponse(liked=liked, likes_count=likes_count)

# 点赞帖子
@router.post("/posts/{post_id}/like", response_model=LikeResponse)
def like_post(
        session: SessionDep,
        current_user: CurrentUser,
        post_id: UUID
) -> Any:
    # 检查帖子是否存在
    post = session.get(CommunityPost, post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")

    # 检查是否已经点赞
    existing_like = session.exec(
        select(PostLike)
        .where(PostLike.post_id == post_id)
        .where(PostLike.user_id == current_user.id)
    ).first()

    if existing_like:
        # 如果已经点赞，则取消点赞
        session.delete(existing_like)
        # 这里同步减1
        post.likes = max(0, (post.likes or 1) - 1)
        liked = False
    else:
        # 如果未点赞，则添加点赞
        new_like = PostLike(post_id=post_id, user_id=current_user.id)
        session.add(new_like)
        # 这里同步加1
        post.likes = (post.likes or 0) + 1
        liked = True

    session.add(post)  # 提交帖子变化
    session.commit()
    session.refresh(post)

    # 获取最新点赞数（可以直接用post.likes了！）
    likes_count = post.likes

    return LikeResponse(liked=liked, likes_count=likes_count)
# -----------------------------------
# 评论 Comment 接口
# -----------------------------------

# 创建评论
@router.post("/comments", response_model=CommentPublic)
def create_comment(session: SessionDep, current_user: CurrentUser, comment_in: CommentCreate) -> Any:
    comment = Comment.model_validate(comment_in, update={"user_id": current_user.id})
    session.add(comment)
    session.commit()
    session.refresh(comment)
    return comment

# 获取帖子评论
@router.get("/comments/{post_id}", response_model=list[CommentPublic])
def read_comments_by_post(session: SessionDep, post_id: uuid.UUID) -> Any:
    query = (
        select(Comment)
        .where(Comment.post_id == post_id)
        .options(selectinload(Comment.user))
        .order_by(Comment.created_at.asc())
    )

    # 执行查询并打印一下结果，方便调试
    comments = session.exec(query).all()
    for comment in comments:
        print(f"Comment ID: {comment.id}, User: {comment.user}")

    return comments


# 点赞评论
@router.post("/comments/{comment_id}/like", response_model=LikeResponse)
def like_comment(
        session: SessionDep,
        current_user: CurrentUser,
        comment_id: UUID
) -> Any:
    # 检查评论是否存在
    comment = session.get(Comment, comment_id)
    if not comment:
        raise HTTPException(status_code=404, detail="Comment not found")

    # 检查是否已经点赞
    existing_like = session.exec(
        select(CommentLike)
        .where(CommentLike.comment_id == comment_id)
        .where(CommentLike.user_id == current_user.id)
    ).first()

    if existing_like:
        # 如果已经点赞，则取消点赞
        session.delete(existing_like)
        # 这里同步减1
        comment.likes = max(0, (comment.likes or 1) - 1)
        liked = False
    else:
        # 如果未点赞，则添加点赞
        new_like = CommentLike(comment_id=comment_id, user_id=current_user.id)
        session.add(new_like)
        # 这里同步加1
        comment.likes = (comment.likes or 0) + 1
        liked = True

    session.add(comment)  # 提交评论变化
    session.commit()
    session.refresh(comment)

    # 直接使用 comment.likes
    likes_count = comment.likes

    return LikeResponse(liked=liked, likes_count=likes_count)

# 获取评论点赞状态
@router.get("/comments/{comment_id}/like-status", response_model=LikeResponse)
def get_comment_like_status(
        session: SessionDep,
        current_user: CurrentUser,
        comment_id: UUID
) -> Any:
    # 检查评论是否存在
    comment = session.get(Comment, comment_id)
    if not comment:
        raise HTTPException(status_code=404, detail="Comment not found")

    # 检查用户是否已点赞
    liked = session.exec(
        select(CommentLike)
        .where(CommentLike.comment_id == comment_id)
        .where(CommentLike.user_id == current_user.id)
    ).first() is not None

    # 直接使用 comment.likes 而不是重新统计
    likes_count = comment.likes


    return LikeResponse(liked=liked, likes_count=likes_count)